package huas.ant.controller;

import huas.ant.entity.Admin;
import huas.ant.common.Result;
import huas.ant.properties.JwtProperties;
import huas.ant.service.AdminService;
import huas.ant.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 注册接口
     */
    @PostMapping("/register")
    public Result register(@RequestBody Admin admin){
        log.info("传递的注册信息为：{}",admin);
        Admin a =adminService.findByAdminAccount(admin.getAdminAccount());
        //判断，如果找到用户说明用户账号重复，没有就注册
        if(a == null){
            adminService.register(admin);
            return Result.success();
        }
        return Result.error("注册失败，该用户账号已存在");
    }

    /**
     * 登录接口
     */
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin){
        log.info("传递的登录信息为:{}",admin);
        Admin a = adminService.login(admin);
        log.info("登录成功");

        //登录成功，生成JWT令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put("adminId",a.getId());
        String jwt = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        return Result.success(jwt);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result logout(){
        log.info("退出登录");
        return Result.success();
    }
}
